package com.hou.hpsj_springboot.controller;

import com.hou.hpsj_springboot.entity.R;
import com.hou.hpsj_springboot.service.InputFileService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

@RestController
@RequestMapping("file")
public class InputFileController {

    @Resource
    private InputFileService inputFileService;

    @RequestMapping("upload")
    public R upLoad(@RequestBody byte[] file , String fileName) throws IOException {
        System.out.println("文件名"+fileName+"文件大小:"+file.length+"字节");
        FileOutputStream fileOutputStream = new FileOutputStream("C:/upload/"+fileName);
        fileOutputStream.write(file);
        fileOutputStream.close();
        return R.ok();
    }

    @GetMapping("{fileName}")
    public void getFileName(@PathVariable("fileName") String fileName, HttpServletResponse response) throws IOException {
        //I流
        FileInputStream fileInputStream = new FileInputStream("C:/upload/" + fileName);
        //O流
        ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("video/mp4");
//        response.setContentType("image/png");
//        response.setContentType("image/jpg");

        //IO读写
        byte[] data = new byte[1024];
        int len;
        while ((len = fileInputStream.read(data)) != -1) {
            outputStream.write(data, 0, len);
        }
        outputStream.close();
        fileInputStream.close();

        inputFileService.addFile("file/"+fileName);
    }

}
